package com.joymart.common.utils;

import com.joymart.common.error.handling.JoymartBusinessException;
import org.springframework.lang.Nullable;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;
import java.util.function.Supplier;

public class SecurityUtils {
    private SecurityUtils() {
    }

    @Nullable
    public static String getCurrentUserId(){
        return Optional.ofNullable(SecurityContextHolder.getContext())
                .map(SecurityContext::getAuthentication)
                .map(Authentication::getPrincipal)
                .map(Object::toString)
                .orElse(null);
    }

    public static void checkCurrentUserIsAny(Supplier<String>... suppliers ) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication.getAuthorities().stream().anyMatch(grantedAuthority -> grantedAuthority.getAuthority().equals("ROLE_PARTY_A"))) {
            return;
        }
        String userId = authentication.getPrincipal().toString();
        for (Supplier<String> supplier : suppliers) {
            if(supplier.get().equals(userId)) {
                return;
            }
        }
        throw new JoymartBusinessException("暂无数据权限");
    }

    public static void requiresRestAuthority(String restAuthorityName) {
        Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
                .map(Authentication::getAuthorities)
                .filter(authList->authList.contains(new SimpleGrantedAuthority(restAuthorityName)))
                .orElseThrow(()->new AccessDeniedException("暂无权限"));
    }
}
